﻿using NetTaste;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace CodeGenerate.Model
{
    public class CodeTable
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }
        public int DbId { get; set; }
        public string ClassName { get; set; }
        public string TableName { get; set; }
        [SugarColumn(IsNullable = true)]
        public string Description { get; set; }
        public DateTime CreateTime { get; set; }
        public DateTime PreUpdateTime { get; set; }
        public DateTime UpdateTime { get; set; }
        public bool IsDeleted { get; set; }
        public bool IsLock { get; set; }

        public List<CodeColumns> Columns { get; set; }

        public static CodeTable GetTableInfo(string sheetName, SqlSugarClient db)
        {
            var tableInfo = db.DbMaintenance.GetTableInfoList().FirstOrDefault(t => t.Name == sheetName);
            if (tableInfo == null) return null;

            var obj = new CodeTable
            {
                Description = tableInfo.Description,
                TableName = tableInfo.Name
            };
            obj.ClassName = CodeCommon.Convert2TF(obj.TableName);

            obj.Columns = InitColumns(sheetName, db);

            return obj;
        }

        private static List<CodeColumns> InitColumns(string sheetName, SqlSugarClient db)
        {

            List<CodeColumns> re = [];

            var cols = db.DbMaintenance.GetColumnInfosByTableName(sheetName, false);

            foreach (var col in cols)
            {
                re.Add(new CodeColumns()
                {
                    ClassProperName = CodeCommon.Convert2TF(col.DbColumnName),
                    DbColumnName = col.DbColumnName,
                    IsPrimaryKey = col.IsPrimarykey,
                    Description = col.ColumnDescription,
                    CodeType = CodeCommon.DbTypeToCS(col.DataType)
                });
            }
            return re;
        }


    }
}
